package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.datatables.lock.CharItemsReading;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.L1CastleLocation;
import com.lineage.server.model.L1Clan;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.utils.SQLUtil;
import com.lineage.server.world.World;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CastleWarGiftTable {
  private static final Log _log = LogFactory.getLog(CastleWarGiftTable.class);
  
  private static final Map<Integer, ArrayList<Gift>> _gifts = new HashMap<>();
  
  private static CastleWarGiftTable _instance;
  
  public static CastleWarGiftTable get() {
    if (_instance == null)
      _instance = new CastleWarGiftTable(); 
    return _instance;
  }
  
  public void load() {
    Connection cn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("SELECT * FROM `w_城战获胜奖励`");
      rs = ps.executeQuery();
      while (rs.next()) {
        int key = rs.getInt("castle_id");
        int itemid = rs.getInt("itemid");
        int count = rs.getInt("count");
        boolean recover = rs.getBoolean("recover");
        Gift e = new Gift();
        e._itemid = itemid;
        e._count = count;
        e._recover = recover;
        ArrayList<Gift> list = _gifts.get(Integer.valueOf(key));
        if (list == null)
          list = new ArrayList<>(); 
        list.add(e);
        _gifts.put(Integer.valueOf(key), list);
      } 
    } catch (SQLException e2) {
      _log.error(e2.getLocalizedMessage(), e2);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
  }
  
  public boolean isGift(int key) {
    ArrayList<Gift> list = _gifts.get(Integer.valueOf(key));
    return (list != null);
  }
  
  public void get_gift(int key) {
    L1Clan castle_clan = null;
    ArrayList<Gift> list = _gifts.get(Integer.valueOf(key));
    if (list == null)
      return; 
    try {
      castle_clan = L1CastleLocation.castleClan(Integer.valueOf(key));
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
      return;
    } finally {
      if (castle_clan != null) {
        Iterator<Gift> iter = list.iterator();
        while (iter.hasNext()) {
          Gift gift = iter.next();
          if (gift._recover)
            recover_item(gift._itemid); 
          get_gift(castle_clan, gift._itemid, gift._count, gift);
        } 
      } 
    } 
  }
  
  private void get_gift(L1Clan castle_clan, int itemid, int count, Gift gift) {
    try {
      if (castle_clan.getOnlineClanMemberSize() > 0) {
        L1PcInstance[] onlineClanMember;
        int length = (onlineClanMember = castle_clan.getOnlineClanMember()).length;
        int i = 0;
        while (i < length) {
          L1PcInstance tgpc = onlineClanMember[i];
          L1ItemInstance item = ItemTable.get().createItem(itemid);
          if (item != null) {
            item.setCount(count);
            tgpc.getInventory().storeItem(item);
            tgpc.sendPackets((ServerBasePacket)new S_ServerMessage("获得攻城奖励:" + item.getLogName()));
            String[] castleName = { "", "肯特城", "妖魔城", "风木城", "奇岩城", "海音城", "侏儒城", "亚丁城", "狄亚得要塞" };
            RecordTable.get().recordCastleReward(castleName[castle_clan.getCastleId()], tgpc.getName(), 
                item.getLogName(), gift._count, item.getId(), tgpc.getIp());
          } 
          i++;
        } 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  private void recover_item(int itemid) {
    try {
      Collection<L1PcInstance> allpc = World.get().getAllPlayers();
      Iterator<L1PcInstance> iter = allpc.iterator();
      while (iter.hasNext()) {
        L1PcInstance tgpc = iter.next();
        L1ItemInstance t1 = tgpc.getInventory().findItemId(itemid);
        if (t1 != null) {
          if (t1.isEquipped())
            tgpc.getInventory().setEquipped(t1, false, false, false); 
          tgpc.getInventory().removeItem(t1);
          tgpc.sendPackets((ServerBasePacket)new S_ServerMessage(158, t1.getLogName()));
        } 
      } 
      CharItemsReading.get().del_item(itemid);
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
  
  private class Gift {
    private int _itemid;
    
    private int _count;
    
    private boolean _recover = false;
    
    private Gift() {}
  }
}
